package com.example.a828502.sfdialtestdemo;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


import com.example.a828502.Utils.GsonUtils;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * PSTN中间拨号页面  备用页面，目前是只用一个页面实现的
 * Created by 828502 on 2016/5/17.
 */
public class PSTNFragment extends Fragment {

    private Context mContext;
    private ListView mListViewContent;
    private Button mBtnGetList;
    private EditText mTxtURL,mTxtPort;
    private TextView mTxtOK,mTxtTip;
    private MyListAdapter mMyListAdapter;
    private List<ListItem> mList = new ArrayList<ListItem>();
    private final OkHttpClient client = new OkHttpClient();

    String requestIP = "";
    String requestPort = "";

    private final int GETKLISTSUCCESS = 1;
    private final int FAILURE = 0;
    private final int ERRORCODE = 2;
    private final int DIALSUCCESS = 3;
    private final int DELIVEREDSUCCESS = 4;
    private final int NODATA = 5;

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case GETKLISTSUCCESS:
                    if (null!= mList && mList.size()>0){
                        Toast.makeText(mContext, "获取数据成功", Toast.LENGTH_SHORT)
                                .show();
                    }else {
                        Toast.makeText(mContext, "暂无数据", Toast.LENGTH_SHORT)
                                .show();
                    }
                        mMyListAdapter = new MyListAdapter(mContext, mList);
                        mListViewContent.setAdapter(mMyListAdapter);
                        setListener();
                    break;

                case FAILURE:
                    Toast.makeText(mContext, "获取数据失败", Toast.LENGTH_SHORT)
                            .show();
                    break;

                case ERRORCODE:
                    Toast.makeText(mContext, "获取的CODE码不为200！",
                            Toast.LENGTH_SHORT).show();
                    break;
                case DIALSUCCESS:
                    Toast.makeText(mContext, "拨号成功", Toast.LENGTH_SHORT)
                            .show();
                    break;
                case DELIVEREDSUCCESS:
                    doGetTaskListRequest();//请求任务列表
                    Toast.makeText(mContext, "妥投成功", Toast.LENGTH_SHORT)
                            .show();
                    break;
                case NODATA:
                    Toast.makeText(mContext, "暂无数据", Toast.LENGTH_SHORT)
                            .show();
                    break;
                default:
                    break;
            }
        }
    };
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fg_pstn, container,false);
        mContext = this.getActivity();
        mTxtTip = (TextView)view.findViewById(R.id.textTip);
        mTxtTip.setText("PSTN直拨");
        mListViewContent = (ListView) view.findViewById(R.id.listViewContent);

        return view;
    }



    /**
     * 设置监听
     */
    private void setListener() {
        /**
         * 完成按钮监听
         */
        mMyListAdapter.setComBtnOnClickListener(new MyListAdapter.OnComBtnOnClickListener() {

            @Override
            public void OnComBtnOnClickListener(String waybillNO, int position, MyListAdapter.ViewContent viewHolder) {
                doCompleteRequest(waybillNO);
            }
        });

        /**
         * 拨号按钮监听
         */
        mMyListAdapter.setDialBtnOnClickListener(new MyListAdapter.OnDialBtnOnClickListener() {

            @Override
            public void OnDialBtnOnClickListener(String orderNumber, int position, MyListAdapter.ViewContent viewHolder) {
                doDialeRequest(orderNumber);
            }
        });
    }


    /**
     * 获取任务列表
     */

    private String results = "";
    public void doGetTaskListRequest() {

        Request request = new Request.Builder()
                .url("http://10.118.44.71:8080/task/order/all")
                .build();
        Call call = client.newCall(request);


        // 开启异步线程访问网络
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Request request, IOException e) {

            }

            @Override
            public void onResponse(Response response) throws IOException {
                results = response.body().string();
                JSONArray ObjectInfo = null;
                JSONObject object = null;
                try {
                    object = new JSONObject(results);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (null != object) {
                    ObjectInfo = object.optJSONArray("obj");
                }
                mList = GsonUtils.json2Array(ObjectInfo.toString(), ListItem.class);

                Message msg = new Message();
                msg.obj = mList;
                if (null!= mList && mList.size()>0){
                    msg.what = GETKLISTSUCCESS;
                }else {
                    msg.what = NODATA;
                }
                handler.sendMessage(msg);
                Log.i("_+_+_+_+", results);

            }
        });
    }

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    /**
     * 完成 接口请求
     * @param waybillNo
     */
    public void doCompleteRequest(String waybillNo){
        JSONObject jsonParam = new JSONObject();//定义json对象
        try {
            jsonParam.put("waybillNo", waybillNo);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody body = RequestBody.create(JSON, String.valueOf(jsonParam));
        Request request = new Request.Builder()
                .url("http://10.118.44.71:8080/task/order/delivered")
                .post(body)
                .build();

        Call call = client.newCall(request);
        // 开启异步线程访问网络
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Request request, IOException e) {

            }

            @Override
            public void onResponse(Response response) throws IOException {
                results = response.body().string();
                Message msg = new Message();
                msg.what = DELIVEREDSUCCESS;
                handler.sendMessage(msg);


                Log.i("_+_+_+_+", results);

            }
        });



    }

    /**
     * 发送回拨请求
     * @param waybillNO
     */
    public void doDialeRequest(String waybillNO){

        JSONObject jsonParam = new JSONObject();//定义json对象
        try {
            jsonParam.put("waybillNo", waybillNO);
            jsonParam.put("Type", "0");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody body = RequestBody.create(JSON, String.valueOf(jsonParam));
        Request request = new Request.Builder()
                .url("http://10.118.44.71:8080/task/order/sendNetWorkCall")
                .post(body)
                .build();

        Call call = client.newCall(request);
        // 开启异步线程访问网络
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Request request, IOException e) {

            }

            @Override
            public void onResponse(Response response) throws IOException {
                results = response.body().string();
                Message msg = new Message();
                msg.what = DIALSUCCESS;
                handler.sendMessage(msg);

                Log.i("_+_+_+_+", results);

            }
        });


//        Uri uri = Uri.parse("tel:" + waybillNO);
//        Intent intent = new Intent(Intent.ACTION_DIAL, uri);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        this.startActivity(intent);
    }

}
